package exchange;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.LinkedList;
import java.util.logging.Logger;

import org.bukkit.Bukkit;
import org.bukkit.inventory.ItemStack;

public class ExchangeLoader {
	private Connection connection;

	public ExchangeLoader() {
		try {
			Bukkit.getLogger().info("Exchange Loader attempting to connect...");
			Class.forName("com.mysql.jdbc.Driver");
			String url = "jdbc:mysql://localhost/qcraft";
			connection = DriverManager.getConnection(url, "root", "paulisbest");
			Bukkit.getLogger().info("SQL Database Connection Successful!");
		}
		catch (Exception e) {
			Bukkit.getLogger().info("SQL Database Connection Failed!");
		}		
	}

	public ItemList loadItems() {
		ItemList itemList = new ItemList();
		try {
			String query = "SELECT * FROM exchange";
			ResultSet data = connection.prepareStatement(query).executeQuery();
			while (data.next()) {
				String name = data.getString("name");
				int id = data.getInt("id");
				short dataValue = data.getShort("data value");
				int quantity = data.getInt("current supply");
				ItemStack itemstack = new ItemStack(id, 0, dataValue);
				Item item = new Item(name, itemstack, quantity, 0);
				itemList.addItem(item);
			}
		}
		catch (SQLException e) {
			Logger.getLogger("Minecraft").info("Unable to retrieve Exchange items");
		}
		return itemList;
	}
	
	public void addItem(Item item) {
		try {
			String insert = "INSERT INTO exchange(name) VALUES (?)";
			PreparedStatement statement = connection.prepareStatement(insert);
			statement.setString(1, item.getName());
			statement.executeUpdate();
		}
		catch (SQLException e) {
			Bukkit.getLogger().info("Unable to add " + item.getName() + " into the Exchange database!");
		}
	}

	public void saveItem(LinkedList<Page> items) {
		try {
			String update = "UPDATE exchange SET "
			for (Page page : items) {
				for (Item item : page.getItems()) {

				}
			}
		}
		catch (Exception e) {

		}
	}

	public void quit() {

	}
}
